package com.sunrise.gateway.web.core;

import com.dap.commons.Constants;
import com.dap.exception.PlatformException;
import com.dap.oss.UploadService;
import com.dap.oss.config.OSSConfig;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public abstract class OSSEngineBase {
    private static Logger LOGGER = LoggerFactory.getLogger(OSSEngineBase.class);

    @Autowired
    public UploadService uploadService;

    @Autowired
    protected OSSConfig ossConfig;

    protected ServletFileUpload upload;
    public OSSEngineBase() {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
    }

    public List<String> execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        List<String> list = new ArrayList<>();
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    String url = handleFileItem(request, item);
                    list.add(url);
                    item.delete();
                }
            }
        } catch (Exception e) {
            LOGGER.warn("", e);
            throw new PlatformException(Constants.ResponseCode.FILE_UPLOAD_FAILURE);
        }
        return list;
    }

    protected abstract String handleFileItem(HttpServletRequest request, FileItem item) throws Exception;

}
